import React, { useState } from 'react';
import DefaultWayStart from '@/executor/tools/task/start/default';
import { IAssignTask } from '@/ts/core/work/assign';
import useAsyncLoad from '@/hooks/useAsyncLoad';
import { FormEditData, InstanceDataModel } from '@/ts/base/model';
import { AssignTaskContext } from '@/components/DataPreview/assign/index';
import { Empty } from 'antd';
import LoadingView from '@/components/Common/Loading';
import orgCtrl from '@/ts/controller';
import { generateUuid } from '@/ts/base/common';

interface AssignViewType {
  assignTask: IAssignTask;
  finished?: () => void;
}
const AssignStart: React.FC<AssignViewType> = ({ assignTask, finished }) => {
  const [key, setKey] = useState(generateUuid());
  const [loaded, combine] = useAsyncLoad(async () => {
    const work = await assignTask.loadWork(true);
    if (!work) {
      return;
    }
    const node = await work.loadNode();
    if (!node) {
      return;
    }
    let data: Dictionary<FormEditData[]> = {};
    // 如果是变更
    if (assignTask.metadata.previousInstanceId) {
      const detail = await assignTask.loadInstanceDetail(
        assignTask.metadata.previousInstanceId,
      );

      if (detail) {
        const instanceData: InstanceDataModel = JSON.parse(detail.data || '{}');
        data = instanceData.data;
      }
    }
    let instance: InstanceDataModel = {
      data,
      fields: {},
      primary: {},
      node: node,
      rules: [],
      assignTask: assignTask.metadata,
    };
    const draftId = assignTask.metadata.draftId;
    if (draftId) {
      const drafts = await orgCtrl.user.workStagging.find([draftId]);
      if (drafts.length > 0) {
        instance = JSON.parse(drafts[0].data);
      }
    }
    const apply = await work.createApply(undefined, instance, '0', false);
    if (!apply) {
      return;
    }
    return { work, apply };
  });

  async function onFinished(success: boolean, instanceId?: string) {
    if (success) {
      instanceId && (await assignTask.submitAssignTask(instanceId));
      finished && finished();
    }
  }

  if (!loaded)
    return (
      <div className="loading-page">
        <LoadingView text="信息加载中..." />
      </div>
    );
  if (!combine)
    return (
      <div style={{ width: '100%', height: '100%' }}>
        <Empty description="找不到关联办事" />
      </div>
    );
  return (
    <>
      <AssignTaskContext.Provider value={assignTask}>
        <DefaultWayStart
          key={key}
          apply={combine.apply}
          work={combine.work}
          content={assignTask.period + '-' + assignTask.metadata.name}
          onStagging={async (instanceId) => {
            await assignTask.draft(instanceId);
            setKey(generateUuid());
          }}
          finished={(success, instanceId) => {
            if (success && instanceId) {
              onFinished(success, instanceId);
            }
          }}></DefaultWayStart>
      </AssignTaskContext.Provider>
    </>
  );
};

export default AssignStart;
